<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\captcha\Captcha;
use think\facade\Session;
use think\facade\Config;
use think\Db;
use OSS\OssClient;
use OSS\Core\OssException;
use PHPMailer\PHPMailer\PHPMailer;//引入邮件类




/*询盘类*/
class Xunpan extends Base
{
  public function send_inquiry(Request $request){
        $post=$request->post();
        $data['base_data']=$this->base_data;
        $ip=$this->base_data['ip'];

        if(empty($post)){
            $result=['status'=>'0','msg'=>'系统错误请重试','name'=>'no'];
            return json($result);
        }
        if(empty($post['name'])){
            $result=['status'=>'0','msg'=>'填写您的姓名','name'=>'formname'];
            return json($result);
        }
        
        if(empty($post['email'])){
            $result=['status'=>'0','msg'=>'填写您的邮箱','name'=>'formemail'];
            return json($result);
        }

        /*邮箱正则*/
        $t="/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,9})$/";
        if(!preg_match($t, $post['email'])) {
            $result=['status'=>'0','msg'=>'邮箱格式错误','name'=>'formemail'];
            return json($result);
        }
        
        if(empty($post['phone'])){
             $result=['status'=>'0','msg'=>'填写您的手机号','name'=>'formphone'];
            return json($result);
        }
        

        if(!empty($_FILES['file'])){
            if($_FILES['file']['size']>Config::get('app.upload_file_size')){
                $result=['status'=>'0','msg'=>'文件不能超过2M','name'=>'fileNamefrom'];
                return json($result);
            }
            $allowedExts = Config::get('app.allowedExts');//允许上传的图片后缀
            $temp = explode(".", $_FILES["file"]["name"]);
            $extension = end($temp);
            if(!in_array($extension, $allowedExts)){
                $result=['status'=>'0','msg'=>'不在允许的文件格式内','name'=>'fileNamefrom'];
                return json($result);
            }

            $tempurl="static/temp/".$_FILES["file"]["name"]; /*服务器暂时存放目录 上传oss后删除*/
            // 目标路径。
            $object = "formdata/".file_name().".".$extension;
            // 本地文件的完整路径。
            $filePath = $tempurl;
            move_uploaded_file($_FILES["file"]["tmp_name"],$tempurl);
            /*移动到oss*/

            try{
                $ossClient = new OssClient(Config::get('app.accessKeyId'), Config::get('app.accessKeySecret'), Config::get('app.endpoint'));

                $ossClient->uploadFile(Config::get('app.bucket'), $object, $filePath);

                if($extension=='mp4'){ $type=2;}else{ $type=1;}

                unlink($filePath);/*删除占用服务器文件*/

            } catch(OssException $e) {
                $result=['status'=>0,'msg'=>$e->getMessage()];
                return json($result);
            }

            $file_url=Config::get('app.images_host').'/'.$object;
        }else{
            $file_url="";
        }
        if($this->base_data['is_show_code']==true){
            if(empty($post['code'])){
                $result=['status'=>'0','msg'=>'填写验证码','name'=>'formcode'];
                return json($result);
            }
            $captcha = new Captcha();
            if( !$captcha->check($post['code']))
            {
                $result=['status'=>'0','msg'=>'验证码错误','name'=>'formcode'];
                return json($result);
            }
        }
        
        /*根据ip识别国家*/
        $shibieip="https://apis.map.qq.com/ws/location/v1/ip?ip=".$ip."&key=O4DBZ-LI26I-BEPGW-56A6T-FJNLZ-F4BWP";
        $loaction=json_decode(file_get_contents($shibieip),true);
        if($loaction['status']==0){
            $country=$loaction['result']['ad_info']['nation'];
        }else{
            $country="未能识别";
        }

        /*进行数据库插入 在插入后发送一封邮件*/
        $data = ['name' => $post['name'], 'company' => $post['company'],'email' => $post['email'],'phone' => $post['phone'],'comments' => $post['comments'],'file_url' => $file_url,'ip' => $ip,'lasturl' => $post['lasturl'],'nowurl' => $post['nowurl'],'Product_Number' => $post['Product_Number'],'country' => $country,'create_time' => date('Y-m-d H:i:s'),'sales' => isset($post['sales'])?$post['sales']:''];
        $resu=Db::connect('publicdata')->table('lily_enquire')->data($data)->insert();
        if($resu==1){
            $result=['status'=>'1','msg'=>'成功','cs'=>$this->base_data['send_num']+1,'name'=>'no'];
            return json($result);
        }else{
            $result=['status'=>'0','msg'=>'系统错误请重试','name'=>'no'];
            return json($result);
        }
    }

     /*邮件发送接口 每隔30分钟 发送一次邮件*/
    public function send_inquiry_mailto(){
        $enquire=Db::connect('publicdata')->table('lily_enquire')->where([['send_status','=',2]])->select();
        if(empty($enquire)){
            echo 'no data';
        }else{
            foreach ($enquire as $key => $value) {
                $desc="<!DOCTYPE html><html><head><style type='text/css'>tr{height: 30px;line-height: 30px;}tr>:first-child{font-weight: bold;width:auto;}tr>:last-child{font-size: 12px}</style></head><body><table style='width:100%;padding:20px;border:1px solid #ccc'><tr>
    <td>Bearings:</td>
    <td>".$value['nowurl']."</td></tr><tr><td>Name:</td><td>".$value['name']."</td></tr><tr><td>Email:</td>
    <td>".$value['email']."</td></tr><tr>
    <td>Phone:</td><td>".$value['phone']."</td></tr><tr><td>Product Number:</td>
    <td>".$value['Product_Number']."</td></tr>".($value['sales']?"<tr><td>Sales:</td><td>".$value['sales']."</td></tr>":'')."<tr><td>Additional Details:</td>
    <td>".$value['comments']."</td></tr><tr><td>Enclosure</td><td>".$value['file_url']."</td></tr><tr><td>Country:</td><td>". $value['country']."</td></tr><tr style='height:80px;'>
    <td>lasturl:</td><td>".$value['lasturl']."</br>ip: ".$value['ip']."</td></tr></table></body></html>";
                $mailto=$this->mailto(Config::get('mail_shou'),$value['email'],$desc,'中文咨询表单');
                if($mailto==1){
                    Db::connect('publicdata')->table('lily_enquire')->where('id', $value['id'])->update(['send_status' => 1]);
                }
            }
        }
    }


     /*
    发送邮件
    $user为收件人地址
    $title为邮件标题
    $desc为邮件正文提示内容
    $fromname:设置发件人昵称
    */
    public  function mailto($user,$title,$desc,$fromname){
        $default_lang=config('app.default_lang');
        //实例化PHPMailer核心类
        $mail = new PHPMailer();

        //$mail->SMTPDebug = 1;#是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
        $mail->isSMTP(); #使用smtp鉴权方式发送邮件
        $mail->SMTPAuth = true; #smtp需要鉴权 这个必须是true
        $mail->Host = 'smtp.qq.com'; #链接qq域名邮箱的服务器地址

        $mail->SMTPSecure = 'ssl'; #设置使用ssl加密方式登录鉴权
        $mail->Port = 465; #设置ssl连接smtp服务器的远程服务器端口号

        $mail->CharSet = 'UTF-8'; #设置发送的邮件的编码
        $mail->FromName = $fromname; #设置发件人昵称 显示在收件人邮件的发件人邮箱地址前的发件人姓名
        $mail->Username = Config::get('mail_username'); #smtp登录的账号
        $mail->Password = Config::get('mail_password'); #smtp登录的密码 使用生成的授权码
        $mail->From = Config::get('mail_username'); #设置发件人邮箱地址 同登录账号

         //邮件正文是否为html编码
        $mail->isHTML(true);
        //设置收件人邮箱地址 添加多个收件人 则多次调用方法即可
        $mail->addAddress($user);

        //添加该邮件的主题
        $mail->Subject = $title;
         //添加邮件正文
        $mail->Body = $desc;
       //发送邮件 返回状态
        if($mail->send()){
            return 1;
        }else{
            return 2;
        }
    }

    /*订阅邮箱*/
    public function subscribe_email(Request $request){
        $post=$request->post();
        $default_lang=config('app.default_lang');
        $data['base_data']=$this->base_data;
        $ip=$this->base_data['ip'];
        if(empty($post)){
            $result=['status'=>'0','msg'=>lang('System error, please try again'),'name'=>'no'];
            return json($result);
        }

        if(empty($post['email'])){
            $result=['status'=>'0','msg'=>lang('Please Fill In Your Email'),'name'=>'subscribe_email'];
            return json($result);
        }

        /*邮箱正则*/
        $t="/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,9})$/";
        if(!preg_match($t, $post['email'])) {
            $result=['status'=>'0','msg'=>lang('The mailbox format is incorrect'),'name'=>'subscribe_email'];
            return json($result);
        }



        $is_subscribe=Db::connect('publicdata')->table('lily_subscribe')->where([['status','=',1],['email','=',$post['email']]])->count('id');

        if($is_subscribe>0){
            $result=['status'=>'0','msg'=>lang('This email is already subscribed'),'name'=>'subscribe_email'];
            return json($result);
        }

        /*进行数据库插入 在插入后发送一封邮件*/
        $data = ['email' => $post['email'],'ip' => $ip,'create_time' => date('Y-m-d H:i:s')];
        $resu=Db::connect('publicdata')->table('lily_subscribe')->data($data)->insert();
        if($resu==1){
            $result=['status'=>'1','msg'=>lang('successfully'),'name'=>'no'];
            return json($result);
        }else{
            $result=['status'=>'0','msg'=>lang('System error, please try again'),'name'=>'no'];
            return json($result);
        }
    }

    /*网站发送询盘和联系我们*/
    public function become_distributor(Request $request){
        $post=$request->post();
        $data['base_data']=$this->base_data;
        $ip=$this->base_data['ip'];

        if(empty($post)){
            $result=['status'=>'0','msg'=>lang('System error, please try again')];
            return json($result);
        }
        if(empty($post['name'])){
            $result=['status'=>'0','msg'=>lang('Please Fill In Your Name')];
            return json($result);
        }
        if(empty($post['company'])){
            $result=['status'=>'0','msg'=>lang('Please Fill In Your Company')];
            return json($result);
        }

        if(empty($post['phone'])){
            $result=['status'=>'0','msg'=>lang('Please Fill In Your Phone')];
            return json($result);
        }

        if(empty($post['email'])){
            $result=['status'=>'0','msg'=>lang('Please Fill In Your Email')];
            return json($result);
        }
        /*邮箱正则*/
        $t="/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,9})$/";
        if(!preg_match($t, $post['email'])) {
            $result=['status'=>'0','msg'=>lang('The mailbox format is incorrect')];
            return json($result);
        }

        if(empty($post['country'])){
            $result=['status'=>'0','msg'=>lang('Choose Your Country')];
            return json($result);
        }
        if(empty($post['main_products'])){
            $result=['status'=>'0','msg'=>lang('Fill In The Main Products Of Your Company')];
            return json($result);
        }
        if(empty($post['comments'])){
            $result=['status'=>'0','msg'=>lang('Please Fill In Comments')];
            return json($result);
        }
        $start=date("Y-m-d 00:00:00",time());
        $end=date("Y-m-d H:i:s",time());
        $cishu=Db::connect('publicdata')->table('lily_distributor')->where([['status','=',1],['create_time','>=',$start],['create_time','<=',$end],['ip','=',$ip]])->count('id');
        if($cishu>Config::get('app.v_code_num')){
            if(empty($post['code'])){
                $result=['status'=>'0','msg'=>lang('Please Fill In Verification Code')];
                return json($result);
            }
            $captcha = new Captcha();
            if( !$captcha->check($post['code']))
            {
                $result=['status'=>'0','msg'=>lang('Incorrect Verification code')];
                return json($result);
            }
        }
        $data = ['name' => $post['name'], 'company' => $post['company'],'email' => $post['email'],'phone' => $post['phone'],'comments' => $post['comments'],'ip' => $ip,'lasturl' => $post['lasturl'],'country' => $post['country'],'main_products' => $post['main_products'],'employees_number' => $post['employees_number'],'sales' => $post['sales'],'create_time' => date('Y-m-d H:i:s')];
        $resu=Db::connect('publicdata')->table('lily_distributor')->data($data)->insert();
        if($resu==1){
            $result=['status'=>'1','msg'=>lang('Submitted successfully')];
            return json($result);
        }else{
            $result=['status'=>'0','msg'=>lang('System error, please try again')];
            return json($result);
        }


    }

    /*邮件发送接口 每隔30分钟 发送一次邮件*/
    public function become_distributor_mailto(){
        $enquire=Db::connect('publicdata')->table('lily_distributor')->where([['send_status','=',2]])->select();
        if(empty($enquire)){
            echo 'no data';
        }else{
            foreach ($enquire as $key => $value) {
                $desc="<!DOCTYPE html><html><head><style type='text/css'>tr{height: 30px;line-height: 30px;}tr>:first-child{font-weight: bold;width:auto;}tr>:last-child{font-size: 12px}</style></head><body><table style='width:100%;padding:20px;border:1px solid #ccc'><tr><td>Name:</td><td>".$value['name']."</td></tr><tr><td>Email:</td>
    <td>".$value['email']."</td></tr><tr>
    <td>Company:</td><td>".$value['company']."</td></tr><tr>
    <td>Phone:</td><td>".$value['phone']."</td></tr><tr><td>Main Products:</td>
    <td>".$value['main_products']."</td></tr><tr><td>Employees Number:</td>
    <td>".$value['employees_number']."</td></tr><tr><td>Sales:</td>
    <td>".$value['sales']."</td></tr><tr><td>Additional Details:</td>
    <td>".$value['comments']."</td></tr><tr><td>Country:</td><td>". $value['country']."</td></tr><tr style='height:80px;'>
    <td>lasturl:</td><td>".$value['lasturl']."</br>ip: ".$value['ip']."</td></tr></table></body></html>";

                $mailto=$this->mailto(Config::get('mail_shou'),$value['email'],$desc,'英文站申请经销商');
                if($mailto==1){
                    Db::connect('publicdata')->table('lily_distributor')->where('id', $value['id'])->update(['send_status' => 1]);
                }
            }
        }
    }

    public function verify(Request $request){
        $config =    [
// 验证码字体大小
            'fontSize'    =>    30,
// 验证码位数
            'length'      =>    4,
// 关闭验证码杂点
            'useNoise'    =>    false,
        ];
        ob_clean();
        $captcha = new Captcha($config);
        $code=$captcha->entry();
        return  $code;
    }



}